package com.Sing.Controller;

import com.Sing.Pojo.Reader;
import com.Sing.Service.ReaderService;
import com.Sing.Utils.Constant;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

@Controller
public class ReaderController {

    private ReaderService readerService;
    @Autowired
    @Qualifier("readerServiceImpl")
    public void setReaderService(ReaderService readerService) {
        this.readerService = readerService;
    }

    // 跳转到 readerIndex 的页面
    @RequestMapping("/readerIndex")
    public String readerIndexJump(){

        return "reader/readerIndex";
    }

    /**
     * 查询数据，并返回给前端页面
     * @param username 查询的子条件 ： 读者名
     * @param readerNumber 查询的子条件 ： 读者编码
     * @param tel 查询的子条件 ： 电话
     * @param limit 查询的子条件 ： 分页大小
     * @param page 查询的子条件 ： 起始页
     * @return 以 HashMap 的形式返回给前端
     */
    @RequestMapping("/readerAll")
    @ResponseBody
    public HashMap<String, Object> readerAll( String username, String readerNumber, String tel, String limit, String page ){
        HashMap<String, Object> resultMap = new HashMap<>();
        HashMap<String, Object> paramMap = new HashMap<>();

        int pageSize = Integer.parseInt( limit );
        int pageContext = ( Integer.parseInt( page ) - 1 ) * pageSize;

        if ( username == null || username.equals( "" ) ){
            username = null;
        } else {
            username = "%" + username + "%";
        }

        if ( tel == null || tel.equals( "" ) ){
            tel = null;
        } else {
            tel = "%" + tel + "%";
        }

        if ( readerNumber == null || readerNumber.equals( "" ) ){
            readerNumber = null;
        } else {
            readerNumber = "%" + readerNumber + "%";
        }

        paramMap.put( "username", username );
        paramMap.put( "readerNumber", readerNumber );
        paramMap.put( "tel", tel );
        paramMap.put( "pageContext", pageContext );
        paramMap.put( "pageSize", pageSize );

        ArrayList<Reader> readerArrayList = readerService.getAllData(paramMap);

        resultMap.put( "count", readerService.getContext( paramMap ) );
        resultMap.put( "data", readerArrayList );
        resultMap.put( "code", 0 );

        return resultMap;
    }

    // 跳转至用户修改的页面
    @RequestMapping("/queryReaderInfoById")
    public String queryReaderInfoByIdJump( String id, HttpServletRequest req, Model model ){

        Reader reader = readerService.queryReaderById( Integer.parseInt( id ) );

        // 将待修改的用户 ID 存入 Session 中
        req.getSession().setAttribute( Constant.ReaderId, id );
        model.addAttribute( "info", reader );

        return "reader/updateReader";
    }

    // 提交用户修改
    @RequestMapping("/updateReaderSubmit")
    @ResponseBody
    public HashMap<String,Object> updateReaderSubmit( @RequestBody(required = false) Reader reader, HttpServletRequest req ){
        HashMap<String, Object> resultMap = new HashMap<>();
        HashMap<String, Object> paramMap = new HashMap<>();

        // 将存入 Session 中的 Id 取出
        String readerId = (String) req.getSession().getAttribute( Constant.ReaderId );
        int id = Integer.parseInt( readerId );

        paramMap.put( "id", id );

        String readerNumber = reader.getReaderNumber();
        String username = reader.getUsername();
        String realName = reader.getRealName();
        String sex = reader.getSex();
        Date birthday = reader.getBirthday();
        String tel = reader.getTel();
        String email = reader.getEmail();

        paramMap.put( "readerNumber", readerNumber );
        paramMap.put( "username", username );
        paramMap.put( "realName", realName );
        paramMap.put( "sex", sex );
        paramMap.put( "birthday", birthday );
        paramMap.put( "tel", tel );
        paramMap.put( "email", email );

        boolean flag = readerService.updateData(paramMap);

        if ( flag ){
            resultMap.put( "code", 0 );
            // 如果执行成功，就将 Session 中存储的 Id 删除
            req.getSession().removeAttribute( Constant.ReaderId );
        }

        return resultMap;
    }

    // 跳转到提交用户添加
    @RequestMapping("/readerAdd")
    public String addUserJump(){

        return "reader/readerAdd";
    }

    // 提交用户添加
    @RequestMapping("/addReaderSubmit")
    @ResponseBody
    public HashMap<Object,Object> addUserCommit( @RequestBody Reader reader ){
        HashMap<Object, Object> resultMap = new HashMap<>();

        // 设置数据 ID 为当前数据总量 + 1
        reader.setId( readerService.getContext(null) + 1 );
        // 设置默认密码 12345
        reader.setPassword( "12345" );
        // 设置注册日期
        reader.setRegisterDate( new Date() );

        if ( readerService.addReader( reader ) ){
            resultMap.put("code","0");
        } else {
            resultMap.put( "msg", "添加失败" );
        }

        return resultMap;
    }

    // 执行用户的删除
    @RequestMapping("/deleteReader")
    @ResponseBody
    public HashMap<Object,Object> deleteReader( String ids ){
        HashMap<Object, Object> resultMap = new HashMap<>();

        // ids 又可能是一个字符串，因此将其拆分为数组，挨个遍历删除
        boolean flag = true;
        String[] tempIds = ids.split(",");
        for ( String temp : tempIds ){
            // 将拆分出的数据转换为 Integer 型的数据，再进行删除
            // 如果删除失败，结束执行
            if ( ! readerService.deleteReader( Integer.parseInt( temp ) ) ){
                flag = false;
                break;
            }
        }

        if ( flag ){
            resultMap.put( "code", "0" );
        }

        return resultMap;
    }

    // 将 String 转换为 Data
    private Date StringToDate( String str ){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Date date = null;
        try {
            date = simpleDateFormat.parse( str );
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return date;
    }
}
